﻿var username = "",
    superadmin = false,
    machucvu = "",
    maphongban = "",
    makhoa = "";
var MsErrorEmpty = "&nbsp;&nbsp;Nhập (chọn) giá trị!";
var MsError = "&nbsp;&nbsp;Có lỗi xảy ra!";
var MsErrorTon = "&nbsp;&nbsp;Tồn kho không đủ!";
var MsErrorNegative = "&nbsp;&nbsp;Lớn hơn 0!";
var MsErrorFormatDate = "&nbsp;&nbsp;Không đúng định dạng!";
var validator;

(function ($) {
    $.fn.selectpicker.defaults = {
        noneSelectedText: "Chọn",
        noneResultsText: "Không tìm thấy từ khóa ",
        countSelectedText: function (numSelected, numTotal) {
            return "{0} giá trị được chọn";
        },
        maxOptionsText: function (numAll, numGroup) {
            var arr = [];
            arr[0] = (numAll === 1) ? "Limit reached ({n} item max)" : "Limit reached ({n} items max)";
            arr[1] = (numGroup === 1) ? "Group limit reached ({n} item max)" : "Group limit reached ({n} items max)";
            return arr;
        },
        selectAllText: "Chọn tất cả",
        deselectAllText: "Bỏ chọn",
        multipleSeparator: ", "
    };
    $.fn.modal.defaults.spinner = $.fn.modalmanager.defaults.spinner =
        "<div class=\"loading-spinner\" style=\"width: 200px; margin-left: -100px;\">" +
        "<div class=\"progress progress-striped active\">" +
        "<div class=\"progress-bar\" style=\"width: 100%;\"></div>" +
        "</div>" +
        "</div>";
    $.fn.modal.defaults.maxHeight = function () {
        return $(window).height() - 80;
    };
}(jQuery));

$(function () {
    username = CheckSession();
    if (username === "") {
        window.location = "/";
        return;
    }
    var dataTaiKhoan = SelectTaiKhoanById(username);
    if (dataTaiKhoan.length > 0) {
        superadmin = dataTaiKhoan[0].SuperAdmin === 0 ? false : true;
        machucvu = dataTaiKhoan[0].MaChucVu;
        maphongban = dataTaiKhoan[0].MaPhongBan;
        makhoa = dataTaiKhoan[0].MaKhoa;
    }
    $("select").selectpicker({
        style: "btn-info",
        size: 10
    });
    $("select").on("change", function () {
        $(this).valid();
    });
    $("input:text:not(.input-block-level):first").focus();
    $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)").bind("keydown", function (e) {
        var n = $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)").length;
        if (e.which === 13 || e.which === 39) {
            e.preventDefault();
            n = $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)").length;
            var nextIndex = $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)").index(this) + 1;
            if (nextIndex < n) {
                $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)")[nextIndex].focus();
            }
        } else if (e.which === 37) {
            e.preventDefault();
            var prevIndex = $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)").index(this) - 1;
            if (prevIndex < n && prevIndex >= 0) {
                $("input:text:not(.input-block-level), .dropdown-toggle:not(.disabled)")[prevIndex].focus();
            }
        }
    });
    $("input, a, button").bind("keydown", function (e) {
        var n = $("input, a, button").length;
        var status;
        if (e.which === 39) {
            e.preventDefault();
            status = true;
            if ($(this).is("input:text")) {
                if ($(this).val().length !== 0) {
                    if ($(this).getSelectionStart() < $(this).val().length) {
                        $(this).setCursorPosition($(this).getSelectionStart() + 1);
                        status = false;
                    }
                }
            }
            if (status === false) return;
            var nextIndex = $("input, a, button").index(this) + 1;
            if (nextIndex < n) {
                $("input, a, button")[nextIndex].focus();
            }
        } else if (e.which === 37) {
            e.preventDefault();
            status = true;
            if ($(this).is("input:text")) {
                if ($(this).val().length !== 0) {
                    if ($(this).getSelectionStart() > 0) {
                        $(this).setCursorPosition($(this).getSelectionStart() - 1);
                        status = false;
                    }
                }
            }
            if (status === false) return;
            var prevIndex = $("input, a, button").index(this) - 1;
            if (prevIndex < n && prevIndex >= 0) {
                $("input, a, button")[prevIndex].focus();
            }
        }
    });
    $("form").each(function () {
        $(this).validate({
            onfocusout: false,
            invalidHandler: function (form, validator) {
                var errors = validator.numberOfInvalids();
                if (errors) {
                    if ($(validator.errorList[0].element).parent().find("select").length > 0) {
                        $(validator.errorList[0].element).parent().find("div.bootstrap-select > button").focus();
                    } else {
                        validator.errorList[0].element.focus();
                    }
                }
            },
            highlight: function (element) {
                $(element).parent().addClass("has-error");
            },
            unhighlight: function (element) {
                $(element).parent().removeClass("has-error");
            },
            errorPlacement: function (error, element) {
                if ($(element).parent().find("select").length > 0) {
                    error.insertAfter($(element).parent().find("div.bootstrap-select"));
                } else if ($(element).parent().hasClass("input-group")) {
                    error.insertAfter($(element).parent());
                } else {
                    error.insertAfter(element);
                }
            },
            errorClass: "help-block",
            ignore: ""
        });
    });
    $(document).bind("ajaxSend", function () {
        $("body").modalmanager("loading");
    }).bind("ajaxComplete", function () {
        $("body").modalmanager("removeLoading");
    });
    $(".modal-fullheight").css({
        'height': $(window).height()
    });
    $("input.ipdate").datetimepicker({
        format: "DD-MM-YYYY",
        language: "vi",
        defaultDate: new Date()
    });
    $("input.ipdatetime").datetimepicker({
        format: "DD-MM-YYYY HH:mm",
        language: "vi",
        defaultDate: new Date()
    });
    $("input.number-price").number(true, 0, ".", ",").css({
        'text-align': "right"
    });
    $.validator.addMethod("dateFormat", function (value, element) {
        return this.optional(element) || isDate(value);
    }, MsErrorFormatDate);
    $.validator.addMethod("datetimeFormat", function (value, element) {
        return this.optional(element) || isDateTime(value);
    }, MsErrorFormatDate);
    $.validator.addMethod("larger_ton", function (value, element, param) {
        return this.optional(element) || parseInt(value) <= parseInt($(param).val());
    }, MsErrorTon);
    $.validator.addMethod("datediffFormat", function (value, element, param) {
        return this.optional(element) || (((moment(value, "DD-MM-YYYY") - moment($(param).val(), "DD-MM-YYYY")) / 1000 / 60 / 60 / 24) >= 0);
    }, MsErrorFormatDate);
    $.validator.addMethod("number_negative", function (value, element) {
        return this.optional(element) || parseFloat(value) > 0;
    }, MsErrorNegative);
});

function isDate(txtDate) {
    var currVal = txtDate;
    if (currVal === "") return false;
    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
    var dtArray = currVal.match(rxDatePattern);
    if (dtArray == null) return false;
    var dtDay = dtArray[1];
    var dtMonth = dtArray[3];
    var dtYear = dtArray[5];
    if (dtMonth < 1 || dtMonth > 12)
        return false;
    else if (dtDay < 1 || dtDay > 31)
        return false;
    else if ((dtMonth === 4 || dtMonth === 6 || dtMonth === 9 || dtMonth === 11) && dtDay === 31)
        return false;
    else if (dtMonth === 2) {
        var isleap = (dtYear % 4 === 0 && (dtYear % 100 !== 0 || dtYear % 400 === 0));
        if (dtDay > 29 || (dtDay === 29 && !isleap))
            return false;
    }
    return true;
}

function isDateTime(txtDate) {
    var currVal = txtDate;
    if (currVal === "") return false;
    var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})(\/|\s)(\d{1,2})(\/|:)(\d{1,2})$/;
    var dtArray = currVal.match(rxDatePattern);
    if (dtArray == null) return false;
    var dtDay = dtArray[1];
    var dtMonth = dtArray[3];
    var dtYear = dtArray[5];
    var dtHours = dtArray[7];
    var dtMinutes = dtArray[9];
    console.log(dtDay + "-" + dtMonth + "-" + dtYear + " " + dtHours + ":" + dtMinutes);
    if (dtMonth < 1 || dtMonth > 12)
        return false;
    else if (dtDay < 1 || dtDay > 31)
        return false;
    else if ((dtMonth === 4 || dtMonth === 6 || dtMonth === 9 || dtMonth === 11) && dtDay === 31)
        return false;
    else if (dtMonth === 2) {
        var isleap = (dtYear % 4 === 0 && (dtYear % 100 !== 0 || dtYear % 400 === 0));
        if (dtDay > 29 || (dtDay === 29 && !isleap))
            return false;
    }
    if (dtHours < 0 || dtHours > 24)
        return false;
    else if (dtMinutes < 0 || dtMinutes > 59) {
        return false;
    }
    return true;
}

jQuery.fn.getSelectionStart = function () {
    if (this.lengh === 0) return -1;
    var input = this[0];
    var pos = input.value.length;
    if (input.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd("character", input.value.length);
        pos = input.value.lastIndexOf(r.text);
    } else if (typeof (input.selectionStart) != "undefined")
        pos = input.selectionStart;
    return pos;
};

jQuery.fn.setCursorPosition = function (position) {
    if (this.lengh === 0) return this;
    return $(this).setSelection(position, position);
};

jQuery.fn.setSelection = function (selectionStart, selectionEnd) {
    if (this.lengh === 0) return this;
    var input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd("character", selectionEnd);
        range.moveStart("character", selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
};

function ResetControlForm(formid) {
    $(formid).validate().resetForm();
    $(formid).find("div.has-error").each(function () {
        $(this).removeClass("has-error");
    });
    $(formid).find("input[type=text], select").each(function () {
        if ($(this).is("input[type=text]")) {
            $(this).val("");
            if ($(this).hasClass("ipdate")) {
                $(this).data("DateTimePicker").setDate(new Date());
            }
        } else if ($(this).is("select") && !$(this).hasClass("not-reset")) {
            $(this).selectpicker("val", "");
        }
    });
}